package com.eqdd.yiqidian.ui.mine.space

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.MyFragmentPagerAdapter
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.share.JShareDialog
import com.eqdd.yiqidian.share.LinkShareBuilder
import com.eqdd.yiqidian.ui.mine.space.fragment.*
import com.eqdd.yiqidian.utils.GreenDaoUtil
import com.eqdd.yiqidian.utils.PreferenceUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_space_preview.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.toast

/**
 * Created by jhj on 18-7-3.
 */
class OwnerComSpaceActivity : BaseActivity() {
    lateinit var list: ArrayList<String>
    lateinit var fragment: ArrayList<Fragment>
    private var companyId = 0

    private lateinit var visitorProduct: String
    private lateinit var visitorCompany: String
    private lateinit var visitorMessage: String

    override fun initBinding() {
        setContentView(R.layout.activity_space_preview)
        companyId = intent.getIntExtra(Config.COMPANY_ID, -1)
        visitorProduct = "VISITOR_SPACE_PRODUCT_$companyId"
        visitorCompany = "VISITOR_SPACE_COMPANY_$companyId"
        visitorMessage = "VISITOR_SPACE_MESSAGE_$companyId"

        var isCollection = false
        if (companyId == -1) {
            toast("查看企业空间失败")
            finish()
            return
        }

        initTopTitleBar(View.VISIBLE, "企业空间")
        iv_right.visibility = View.VISIBLE
        iv_right.setImageResource(R.mipmap.addg)
        visitor("企业空间", "访问了企业空间", visitorCompany)
        popMenu(listOf("分享", "收藏"), iv_right) { dialog, pos ->
            if (pos == 0) {
                val companyBean = GreenDaoUtil.getCompany();
                val builder = LinkShareBuilder(this)
                builder.setTitle("企业空间")
                        .setText(companyBean.name)
                        .setUrl("https://www.eqidd.com/qiyeSpace/html/companyIndex.html?id=46")
                        .setImageUrl(companyBean.logo)
                        .setSource("企业空间")
                JShareDialog(builder, this).show()
            } else if (pos == 1) {
                if (user.isAdmin >0){
                    OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.COLLECT_ADD)
                            .params("userGuid", user.guid)
                            .params("userCompanyId", user.companyId)
                            .params("objectId", 0)
                            .params("objectType", 0)
                            .params("objectCompanyId", companyId)
                            .execute(object : DialogCallBack<HttpResult<*>>(this) {
                                override fun onSuccess(response: Response<HttpResult<*>>?) {
                                    val result = response?.body()
                                    if (result?.status == 200) {
                                        if (!isCollection) toast("收藏成功")
                                        isCollection = true
                                    } else {
                                        if (!isCollection) toast(result?.msg
                                                ?: "收藏失败")
                                        isCollection = true
                                    }
                                }

                            })
                }
                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MAKER_COLLECT_ADD)
                        .params("userCompanyId", user.companyId)
                        .params("userGuid", user.guid)
                        .params("objectId", 0) //被收藏的id（（企业/创客）产品id）
                        .params("objectType", 0) //0:收藏企业，1：企业产品 ，2：创客产品，3：其他创客
                        .params("objectGuid", "") //如果收藏的是创客，创客guid
                        .params("objectCompanyId", companyId) //被收藏企业id
                        .execute(object : DialogCallBack<HttpResult<*>>(this@OwnerComSpaceActivity) {
                            override fun onSuccess(response: Response<HttpResult<*>>?) {
                                val result = response?.body()
                                if (result?.status == 200) {
                                    if (!isCollection) toast("收藏成功")
                                    isCollection = true
                                } else {
                                    if (!isCollection) toast(result?.msg
                                            ?: "收藏失败")
                                    isCollection = true
                                }
                            }
                        })




            }
        }


        listener()
    }

    override fun initData() {
        list = arrayListOf<String>("日志", "产品信息", "企业信息", "企业文化", "留言")
        fragment = arrayListOf<Fragment>(getFragment(DiaryFragment()), getFragment(ProductFragment()),
                getFragment(InfoFragment()), getFragment(CultureFragment()), getFragment(MessageFragment()))

    }

    override fun setView() {
        // 第二步：为ViewPager设置适配器
        vp_pager.adapter = MyFragmentPagerAdapter(supportFragmentManager, list, fragment)
        //  第三步：将ViewPager与TableLayout 绑定在一起
        tl_tab.setupWithViewPager(vp_pager)

    }


    fun getFragment(fragment: Fragment): Fragment {
        val bundle = Bundle()
        bundle.putString(Config.GUID, user.guid)
        bundle.putInt(Config.COMPANY_ID, companyId)
        bundle.putInt("userCompanyId", user.companyId)
        fragment.arguments = bundle
        return fragment
    }

    fun listener() {
        vp_pager.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
                print(state.toString())
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                print(position.toString())
            }

            override fun onPageSelected(position: Int) {
                if (position == 1) {
                    visitor("产品信息列表", "访问了产品信息列表", visitorProduct)
                } else if (position == 4) {
                    visitor("留言", "访问了留言", visitorMessage)
                }
            }

        })
    }

    private fun visitor(mudular: String, option: String, key: String) {
        val time = PreferenceUtil.find(this, key, String::class.java)
        if (time == null || time.toLong() < System.currentTimeMillis() - 30 * 60 * 1000) {
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.SPACE_VISITOR_ADD)
                    .params("userGuid", user.guid)
                    .params("userCompanyId", user.companyId)
                    .params("companyId", companyId)
                    .params("mudular", mudular)
                    .params("option", option)
                    .execute(object : JsonCallBack<HttpResult<*>>() {
                        override fun onSuccess(response: Response<HttpResult<*>>?) {
                            val result = response?.body()
                            if (result?.status == 200) {
                                PreferenceUtil.save(this@OwnerComSpaceActivity, System.currentTimeMillis().toString(), key)
                                print(mudular)
                            }
                        }
                    })
        }
    }

}